#!/usr/bin/perl
#------------------------------------------------------------------------------
# Project  : Oracle to Postgresql converter
# Name     : ora2pg_scanner
# Author   : Gilles Darold, gilles _AT_ darold _DOT_ net
# Copyright: Copyright (c) 2000-2020 : Gilles Darold - All rights reserved -
# Function : Script used to scan a list of DSN and generate reports
# Usage    : ora2pg_scanner -l dsn_csv_file -o outdir
#------------------------------------------------------------------------------
#
#        This program is free software: you can redistribute it and/or modify
#        it under the terms of the GNU General Public License as published by
#        the Free Software Foundation, either version 3 of the License, or
#        any later version.
# 
#        This program is distributed in the hope that it will be useful,
#        but WITHOUT ANY WARRANTY; without even the implied warranty of
#        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#        GNU General Public License for more details.
# 
#        You should have received a copy of the GNU General Public License
#        along with this program. If not, see < http://www.gnu.org/licenses/ >.
# 
#------------------------------------------------------------------------------
use strict;

use Getopt::Long qw(:config no_ignore_case bundling);

my $VERSION = '21.1';

my @DB_DNS = ();
my $OUTDIR = '';
my $DRYRUN = 0;
my $INPUT_FILE = '';
my $CONF_FILE = '';
my $HELP = 0;
my $ORA2PG_CMD = 'ora2pg';
my $BINPATH = '';
my $SEP = ($^O =~ /MSWin32|dos/i) ? "\\" : "/";
my $COST_UNIT = 5;

# Collect command line arguments
GetOptions
(
	'c|config=s'  => \$CONF_FILE,
	'b|binpath=s' => \$BINPATH,
	'l|list=s'    => \$INPUT_FILE,
	't|test!'     => \$DRYRUN,
        'o|outdir=s'  => \$OUTDIR,
        'u|unit=s'    => \$COST_UNIT,
        'h|help!'     => \$HELP,
);

$OUTDIR = 'output' if (!$OUTDIR);

if (!$INPUT_FILE || !-e $INPUT_FILE || $HELP)
{
	usage();
}

if ($BINPATH)
{
	$BINPATH =~ s/\Q$SEP\E$//;
	if (-e "$BINPATH$SEP$ORA2PG_CMD")
	{
		$ORA2PG_CMD = "$BINPATH$SEP$ORA2PG_CMD";
	}
	else
	{
		die "FATAL: path to ora2pg binary must exists: $BINPATH$SEP$ORA2PG_CMD\n"; 
	}
}

if ($^O =~ /MSWin32|dos/i)
{
	$ORA2PG_CMD = "perl $ORA2PG_CMD";
}

open(IN, $INPUT_FILE) or die "FATAL: can not read file $INPUT_FILE, $!\n";
while (my $l = <IN>)
{
	#"type","schema/database","dsn","user","password","audit users"
	#"MYSQL","sakila","dbi:mysql:host=192.168.1.10;database=sakila;port=3306","root","mysecret"
	#"ORACLE","HR","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager","hr;system;scott"
	# skip header line
	chomp($l);
	$l =~ s/\r//;
	next if ($l !~ /^["]*(MYSQL|ORACLE)["]*,/i);
	$l =~ s/"//gs;
	my @data = split(/,/, $l);
	if ($#data < 4)
	{
		 die "FATAL: wrong number of field at line: $l\n";
	}
	my ($type, $schema, $dsn, $user, $passwd, $audit_user) = split(/,/, $l);
	push(@DB_DNS, { (
				'type' => uc($type),
				'schema' => $schema,
				'dsn' => $dsn,
				'user' => $user,
				'pwd' => $passwd,
				'audit_user' => $audit_user,
				'sid' => '',
				'host' => ''
			)
		}
	);
}
close(IN);

# Create the output directory
if (!$DRYRUN)
{
	if (!-d "$OUTDIR")
	{
		mkdir "$OUTDIR";
	}
	else
	{
		print "FATAL: output directory already exists, $OUTDIR.\n";
		exit 1;
	}
}
else
{
	print "Performing connection test only by retrieving the requested schema or database.\n";
}

# Start to generate call to ora2pg
my $header = ' --print_header';
for (my $i = 0; $i < @DB_DNS; $i++)
{
	$header = '' if ($i > 0);
	$ENV{ORA2PG_USER}     = $DB_DNS[$i]->{user};
	$ENV{ORA2PG_PASSWD} = $DB_DNS[$i]->{pwd};
	# Used to pass additional information to ora2pg command
	my $info = '';
	# Set RDBMS type
	$info = ' -m' if ($DB_DNS[$i]->{type} eq 'MYSQL');
	# Add custom configuration file if set
	$info .= ' -c ' . $CONF_FILE if ($CONF_FILE);
	my $cmd_ora2pg = $ORA2PG_CMD . $info;

	my $audit = '';
	$audit = " --audit_user \"$DB_DNS[$i]->{audit_user}\"" if ($DB_DNS[$i]->{audit_user});
	# Extract SID or db name from the DSN
	# dbi:Oracle:host=foobar;sid=ORCL;port=1521
	# dbi:Oracle:DB
	# dbi:Oracle://192.168.1.10:1521/XE
	# DBI:mysql:database=$db;host=$host
	if ($DB_DNS[$i]->{dsn} =~ m/(?:sid|database)=([^;]+)/ ||
		$DB_DNS[$i]->{dsn} =~ m/dbi:Oracle:([\w]+)$/  ||
		$DB_DNS[$i]->{dsn} =~ m/dbi:Oracle:\/\/[^\/]+\/([\w]+)/ )
	{
		$DB_DNS[$i]->{sid} = $1;
	}
	elsif (!$DB_DNS[$i]->{schema})
	{
		print "WARNING: couldn't determine sid/database name for DSN ". $DB_DNS[$i]->{dsn} .", without explicit schema can not processed this entry. Skiping.\n";
		next;
	}
	else
	{
		$DB_DNS[$i]->{sid} = 'schema';
	}

	# Extract host
	if ($DB_DNS[$i]->{dsn} =~ m/host=([^;]+)/ || $DB_DNS[$i]->{dsn} =~ m/dbi:Oracle:\/\/([^\/]+)/)
	{
		$DB_DNS[$i]->{host} = $1;
		$DB_DNS[$i]->{host} =~ s/:\d$+//;
		$DB_DNS[$i]->{host} .= '_';
	}

	# When no schema or database is set, let Ora2Pg autodetect the list of available schema
	if ($DB_DNS[$i]->{schema} eq '')
	{
		if ($DRYRUN)
		{
			print "Running: $cmd_ora2pg -t SHOW_SCHEMA -s '$DB_DNS[$i]->{dsn}'\n";
			print `$cmd_ora2pg -t SHOW_SCHEMA -s '$DB_DNS[$i]->{dsn}'`;
			print "For each schema returned the following commands will be executed:\n";
			print "    $cmd_ora2pg -t SHOW_REPORT --dump_as_sheet --cost_unit_value $COST_UNIT --estimate_cost$header$audit -s '$DB_DNS[$i]->{dsn}' -n '<schema_returned>' >> $OUTDIR${SEP}dbs_scan.csv\n";
			print "    $cmd_ora2pg -t SHOW_REPORT --dump_as_html --cost_unit_value $COST_UNIT --estimate_cost$audit -s '$DB_DNS[$i]->{dsn}' -n '<schema_returned>' >> \"$OUTDIR${SEP}$DB_DNS[$i]->{host}$DB_DNS[$i]->{sid}_<schema_returned>-report.html\"\n";
		}
		else
		{
			my @schema_list = `$cmd_ora2pg -t SHOW_SCHEMA -s '$DB_DNS[$i]->{dsn}'`;
			foreach my $line (@schema_list)
			{
				my ($type, $schemaname) = split(/\s+/, $line);
				$DB_DNS[$i]->{schema} = $schemaname;
				# Escape some chars for file path use
				$schemaname = quotemeta($schemaname);
				print "Running: $cmd_ora2pg -t SHOW_REPORT --dump_as_sheet --cost_unit_value $COST_UNIT --estimate_cost$header$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> $OUTDIR${SEP}dbs_scan.csv\n";
				`$cmd_ora2pg -t SHOW_REPORT --dump_as_sheet --cost_unit_value $COST_UNIT --estimate_cost$header$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> $OUTDIR${SEP}dbs_scan.csv`;
				$header = '';

				print "Running: $cmd_ora2pg -t SHOW_REPORT --dump_as_html --cost_unit_value $COST_UNIT --estimate_cost$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> \"$OUTDIR${SEP}$DB_DNS[$i]->{host}$DB_DNS[$i]->{sid}_$schemaname-report.html\"\n";
				`$cmd_ora2pg -t SHOW_REPORT --dump_as_html --cost_unit_value $COST_UNIT --estimate_cost$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> "$OUTDIR${SEP}$DB_DNS[$i]->{host}$DB_DNS[$i]->{sid}_$schemaname-report.html"`;
			}
		}
	}
	else
	{
		# Escape some chars for file path use
		my $schemaname = quotemeta($DB_DNS[$i]->{schema});

		if ($DRYRUN)
		{
			print "Running: $cmd_ora2pg -t SHOW_SCHEMA -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}'\n";
			print `$cmd_ora2pg -t SHOW_SCHEMA -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}'`
		}
		else
		{
			print "Running: $cmd_ora2pg -t SHOW_REPORT --dump_as_sheet --cost_unit_value $COST_UNIT --estimate_cost$header$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> $OUTDIR${SEP}dbs_scan.csv\n";
			`$cmd_ora2pg -t SHOW_REPORT --dump_as_sheet --cost_unit_value $COST_UNIT --estimate_cost$header$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> $OUTDIR${SEP}dbs_scan.csv`;
			print "Running: $cmd_ora2pg -t SHOW_REPORT --dump_as_html --cost_unit_value $COST_UNIT --estimate_cost$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> \"$OUTDIR${SEP}$DB_DNS[$i]->{sid}_$schemaname-report.html\"\n";
			`$cmd_ora2pg -t SHOW_REPORT --dump_as_html --cost_unit_value $COST_UNIT --estimate_cost$audit -s '$DB_DNS[$i]->{dsn}' -n '$DB_DNS[$i]->{schema}' >> "$OUTDIR${SEP}$DB_DNS[$i]->{sid}_$schemaname-report.html"`;
		}
	}
}

exit 0;

sub usage
{
	my $msg = shift;

	print "$msg\n" if ($msg);

	print qq{
Usage: ora2pg_scanner -l CSVFILE [-o OUTDIR]

   -b | --binpath DIR: full path to directory where the ora2pg binary stays.
   		Might be useful only on Windows OS.
   -c | --config FILE: set custom configuration file to use otherwise ora2pg
		will use the default: /etc/ora2pg/ora2pg.conf.
   -l | --list FILE : CSV file containing a list of databases to scan with
		all required information. The first line of the file
		can contain the following header that describes the
		format that must be used:

		"type","schema/database","dsn","user","password"

   -o | --outdir DIR : (optional) by default all reports will be dumped to a
		directory named 'output', it will be created automatically.
		If you want to change the name of this directory, set the name
		at second argument.

   -t | --test : just try all connections by retrieving the required schema
		 or database name. Useful to validate your CSV list file.
   -u | --unit MIN : redefine globally the migration cost unit value in minutes.
		 Default is taken from the ora2pg.conf (default 5 minutes).

   Here is a full example of a CSV databases list file:

	"type","schema/database","dsn","user","password"
	"MYSQL","sakila","dbi:mysql:host=192.168.1.10;database=sakila;port=3306","root","secret"
	"ORACLE","HR","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager"

   The CSV field separator must be a comma.

   Note that if you want to scan all schemas from an Oracle instance you just
   have to leave the schema field empty, Ora2Pg will automatically detect all
   available schemas and generate a report for each one. Of course you need to
   use a connection user with enough privileges to be able to scan all schemas.
   For example:

	"ORACLE","","dbi:Oracle:host=192.168.1.10;sid=XE;port=1521","system","manager"

   will generate a report for all schema in the XE instance. Note that in this
   case the SCHEMA directive in ora2pg.conf must not be set.

};
	exit 1;
}

